/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.castor.castor;

import cn.easyplatform.castor.Castor;
import cn.easyplatform.castor.FailToCastObjectException;
import cn.easyplatform.lang.Lang;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

@SuppressWarnings({ "rawtypes" })
public class Number2Enum extends Castor<Number, Enum> {

	@Override
	public Enum cast(Number src, Class<?> toType, String... args)
			throws FailToCastObjectException {
		int v = src.intValue();
		Enum o = null;

		// 首先试图用采用该类型的 fromInt 的静态方法
		try {
			Method m = toType.getMethod("fromInt", int.class);
			if (Modifier.isStatic(m.getModifiers())
					&& toType.isAssignableFrom(m.getReturnType())) {
				o = (Enum) m.invoke(null, v);
			}
		} catch (Exception e) {
		}

		// 搞不定，则试图根据顺序号获取
		if (null == o)
			try {
				for (Field field : toType.getFields()) {
					if (field.getType() == toType) {
						Enum em = (Enum) field.get(null);
						if (em.ordinal() == v)
							return em;
					}
				}
				throw Lang.makeThrow(FailToCastObjectException.class,
						"Can NO find enum value in [%s] by int value '%d'",
						toType.getName(), src.intValue());
			} catch (Exception e2) {
				throw Lang.wrapThrow(e2, FailToCastObjectException.class);
			}

		return o;
	}
}
